/*
 * @Date         : 2022-07-13 23:22:51
 * @LastEditors  : zu1662
 * @LastEditTime : 2022-07-13 23:55:42
 * @Description  : 全局jwt中间件,把 token 转成 user 对象。
 *                 用于前后端统一接口，不同数据的处理。
 * 
 * Copyright © 2022 by zu1662, All Rights Reserved. 
 */
import { Injectable, NestMiddleware } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Response, NextFunction } from "express";
import { IRequestApp } from "src/utils/request/request.interface";

@Injectable()
export class JwtUserMiddleware implements NestMiddleware {
  async use(req: IRequestApp, res: Response, next: NextFunction) {
    const { authorization }= req.headers
    const token = authorization ? authorization.split(" ")[1] : undefined;
    try {
      const tokenUser = await new JwtService().decode(token) as any;
      req.user = tokenUser
    } catch (e) {
      req.user = null
    }
    next();
  }
}
